package middleware

import (
	"net/http"
	"ssr/common"

	"github.com/gin-gonic/gin"
)

func ResponseWrapper() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		if _, exists := c.Get("already_sent"); exists {
			return
		}

		switch c.Writer.Status() {
		case http.StatusOK:
			data, exists := c.Get("response_data")
			if exists {
				common.Success(data).Send(c)
			}
		default:
			common.Fail(c.Writer.Status(), c.Errors.String()).Send(c)
			c.Abort()
		}
	}

}
